package com.tanhua.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.User;
import com.tanhua.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String TOKEN_PREFIX = "TOKEN_";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token==null){
            response.setStatus(401);
        }
        User user = findUserByToken(token);
        if (user==null){
            response.setStatus(401);
            return false;
        }
        UserHolder.setUser(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }

    public User findUserByToken(String token) {
        String userJson = redisTemplate.opsForValue().get(TOKEN_PREFIX + token);
        if (userJson==null){
            return null;
        }
        User user = JSON.parseObject(userJson, User.class);
        return user;
    }
}
